package com.jt.tenant.activity;

import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.jt.tenant.R;
import com.jt.tenant.conn.GetAddFence;
import com.jt.tenant.conn.GetCarGps;
import com.jt.tenant.conn.GetQueryFence;
import com.jt.tenant.conn.GetUpdateFence;
import com.jt.tenant.widget.OnOffView;
import com.zcx.helper.http.AsyCallBack;
import com.zcx.helper.util.UtilToast;
import com.zcx.helper.view.CheckView;

import java.text.DecimalFormat;

/**
 * Created by Administrator on 2016/2/15.
 */
public class FenceActivity extends JTActivity implements CheckView.OnCheckChangeListener ,View.OnClickListener{

    private DecimalFormat decimalFormat = new DecimalFormat("##.##");

    private LatLng temporarylatLng  = new LatLng(45.821143, 126.661377), currentlatLng;

    private int distance = 1000;

    private TextView distanceView;

    private OnOffView inOpen, outOpen;

    private GeocodeSearch geocoderSearch;

    private MapView mapView;

    private AMap aMap;

    private double lat,lon;

    private AsyCallBack asyCallBack = new AsyCallBack(){

        @Override
        public void onSuccess(String toast, int type, Object o) throws Exception {

            if(toast.equals("000")){

                UtilToast.show(context, "设置成功");

                finish();

            }else{

                UtilToast.show(context, "设置失败");

            }

        }

    };

    private GetAddFence getAddFence = new GetAddFence(asyCallBack);

    private GetUpdateFence getUpdateFence = new GetUpdateFence(asyCallBack);

    private GetQueryFence.Fence currentFence;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_fence);

        findViewById(R.id.fence_scope_left).setOnClickListener(this);

        findViewById(R.id.fence_scope_right).setOnClickListener(this);

        findViewById(R.id.fence_affirm).setOnClickListener(this);

        (outOpen = (OnOffView) findViewById(R.id.fence_leave)).setOnCheckChangeListener(this);

        (inOpen = (OnOffView) findViewById(R.id.fence_access)).setOnCheckChangeListener(this);

        distanceView = (TextView) findViewById(R.id.fence_scope_distance);

        distanceView.setText(currentFence == null ? "1Km" : currentFence.rangeNum + "Km");

        mapView = (MapView) findViewById(R.id.fence_map_view);

        mapView.onCreate(savedInstanceState);

        aMap = mapView.getMap();

        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);// 设置地图logo显示在左下方
        mUiSettings.setZoomControlsEnabled(false); //是否显示缩放按钮

        aMap.setOnMapLongClickListener(new AMap.OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng latLng) {

                setLocation(temporarylatLng = latLng);

            }

        });

        geocoderSearch = new GeocodeSearch(this);

        geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {

            private RegeocodeAddress regeocodeAddress;

            @Override
            public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {

                if ((currentlatLng = temporarylatLng) != null && regeocodeResult != null && (regeocodeAddress = regeocodeResult.getRegeocodeAddress()) != null) {

                        getUpdateFence.name = getAddFence.name =regeocodeAddress.getCity() +  regeocodeAddress.getDistrict() + " " + regeocodeAddress.getTownship();

                        getUpdateFence.lat = getAddFence.lat = currentlatLng.latitude + "";

                        getUpdateFence.lng = getAddFence.lng = currentlatLng.longitude + "";

                        getUpdateFence.address_type = getAddFence.address_type = "3";

                        setMarkerCircle(currentlatLng, getUpdateFence.address = getAddFence.address = regeocodeAddress.getFormatAddress(), distance);

                }

            }

            @Override
            public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

            }

        });

        currentFence = (GetQueryFence.Fence) getIntent().getSerializableExtra("Fence");

        new GetCarGps(new AsyCallBack<GetCarGps.Info>(){

            @Override
            public void onSuccess(String toast, int type, GetCarGps.Info info) throws Exception {


                lat = info.lat;
                lon = info.lng;

                aMap.addMarker(new MarkerOptions().position(new LatLng(info.lat, info.lng)).title("").icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                        .decodeResource(getResources(),
                                R.mipmap.car_red))));
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(info.lat, info.lng), 13));

                if(currentFence == null){

//                    setLocation(temporarylatLng = new LatLng(info.lat, info.lng));
//
//                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(temporarylatLng, 13));

                }else{

                    setMarkerCircle(currentlatLng, getUpdateFence.address = currentFence.address, distance = (int) (currentFence.rangeNum * 1000));

                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentlatLng, 13));

                }

            }

        }).execute(this);

        if(currentFence == null){

            ((TextView)findViewById(R.id.tv_title_name)).setText("添加电子围栏");

        } else {

            getUpdateFence.id = currentFence.id;

            inOpen.setCheck((getUpdateFence.in_open = currentFence.inOpen).equals("1"));

            outOpen.setCheck((getUpdateFence.out_open = currentFence.outOpen).equals("1"));

            getUpdateFence.name = currentFence.name;

            getUpdateFence.address = currentFence.address;

            getUpdateFence.lat = currentFence.lat + "";

            getUpdateFence.lng = currentFence.lng + "";

            getUpdateFence.address_type = currentFence.addressType;

            getUpdateFence.range_num = currentFence.rangeNum + "";

            ((TextView)findViewById(R.id.tv_title_name)).setText("修改电子围栏");

            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentlatLng = new LatLng(currentFence.lat, currentFence.lng), 13));

            setMarkerCircle(currentlatLng, getUpdateFence.address = currentFence.address, distance = (int) (currentFence.rangeNum * 1000));

        }

    }

    private void setLocation(LatLng latLng){

        geocoderSearch.getFromLocationAsyn(new RegeocodeQuery(new LatLonPoint(latLng.latitude, latLng.longitude), 200, GeocodeSearch.AMAP));

    }

    private void setMarkerCircle(LatLng latLng, String address, int distance){

        aMap.clear();

        aMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon)).title("").icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory
                .decodeResource(getResources(),
                        R.mipmap.car_red))));

        aMap.addMarker(new MarkerOptions().position(latLng).snippet(address).draggable(true));

        aMap.addCircle(new CircleOptions().center(latLng).radius(distance).strokeColor(Color.parseColor("#501873f8")).fillColor(Color.parseColor("#501592ff")).strokeWidth(2));



        distanceView.setText((getUpdateFence.range_num = getAddFence.range_num = decimalFormat.format((double) distance / (double) 1000)) + "Km");

    }

    @Override
    public void onCheckChange(View view, boolean b) {

        switch (view.getId()){

            case R.id.fence_leave:

                getUpdateFence.out_open = getAddFence.out_open = b ? "1" : "0";

                break;

            case R.id.fence_access:

                getUpdateFence.in_open = getAddFence.in_open = b ? "1" : "0";

                break;

        }

    }

    public void onClick(View view){

        switch (view.getId()){

            case R.id.fence_scope_left:

                setMarkerCircle(currentlatLng, getUpdateFence.address, distance = distance - 100 > 500 ? distance - 100 : 500);

                break;

            case R.id.fence_scope_right:

                setMarkerCircle(currentlatLng, getUpdateFence.address, distance += 100);

                break;

            case R.id.fence_affirm:

                if(currentFence == null){

                    getAddFence.execute(this);

                }else{

                    getUpdateFence.execute(this);

                }

                break;

        }

    }

    @Override
    protected void onResume() {

        super.onResume();

        mapView.onResume();

    }

    @Override
    protected void onPause() {

        super.onPause();

        mapView.onPause();

    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

        mapView.onDestroy();

    }

}